# Create your tasks here

# from demoapp.models import Widget

from datetime import timedelta
from celery import shared_task
from .models import Order
from django.utils import timezone

@shared_task
def add(x, y):
    return x + y


@shared_task
def mul(x, y):
    return x * y


@shared_task
def xsum(numbers):
    return sum(numbers)


# @shared_task
# def count_widgets():
#     return Widget.objects.count()


# @shared_task
# def rename_widget(widget_id, name):
#     w = Widget.objects.get(id=widget_id)
#     w.name = name
#     w.save()

@shared_task
def check_order_expired(order_id):
    order = Order.objects.get(id = order_id)
    expired_time = order.pay_time + timedelta(seconds=30)
    if timezone.now() > expired_time:
        order.pay_status = "TRADE_CLOSE"
        order.save()
        return f"order {order.id} 过期"
    
    return f"order {order.id} 未过期"

@shared_task
def batch_check_expired_orders():
    orders = Order.objects.filter(pay_status="PAYING")
    for order in orders:
        check_order_expired.delay(order.id)   